﻿using System.Runtime.InteropServices;
using System.Text;

namespace ToolUtil
{
    public class IniFunc
    {

        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(byte[] section, byte[] key, byte[] val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(byte[] section, byte[] key, byte[] def, byte[] retVal, int size, string filePath);

        //与ini交互必须统一编码格式
        private static byte[] getBytes(string s, string encodingName)
        {
            return null == s ? null : Encoding.GetEncoding(encodingName).GetBytes(s);
        }
        public static string getString(string section, string key, string def, string filename)
        {
            StringBuilder sb = new StringBuilder(1024);
            byte[] buffer = new byte[1024];
            int count = GetPrivateProfileString(getBytes(section, "utf-8"), getBytes(key, "utf-8"), getBytes(def, "utf-8"), buffer, 1024, filename);
            return Encoding.GetEncoding("utf-8").GetString(buffer, 0, count).Trim();
        }

        public static void writeString(string section, string key, string val, string filename)
        {
            WritePrivateProfileString(getBytes(section, "utf-8"), getBytes(key, "utf-8"), getBytes(val, "utf-8"), filename);
        }
    }
}
